package org.carpediem.conman.dao;

import org.carpediem.conman.entity.Contact;
import org.carpediem.conman.entity.Note;
import org.carpediem.schema.conman.BNoteInfo;
import org.carpediem.schema.conman.NoteInfo;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Mark Petrovic
 */
public class NoteDaoImpl extends NoteDao {
/*    private HibernateTemplate hibernateTemplate;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }*/

    public Note get(long id) {
        return (Note) hibernateTemplate.get(Note.class, id);
    }

    public List<Note> getByOwner(final Contact contact) {
        Object noteList = hibernateTemplate.execute(new ByOwner(contact));
        return (List<Note>) noteList;
    }

    public Note add(Contact contact, NoteInfo noteInfo) {
        Note note = new Note();
        BNoteInfo bInfo = noteInfo.getNote();
        note.setNote(bInfo.getNote());
        note.setUri(getS3Persister().noteUri(note));
        contact.add(note);

        hibernateTemplate.saveOrUpdate(note);

        getS3Persister().enqueue(contact);

        index(contact);

        return note;
    }

    private class ByOwner implements HibernateCallback {
        private Contact contact;

        public ByOwner(Contact contact) {
            this.contact = contact;
        }

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery("from Note where contact =:aContact");
            query.setParameter("aContact", contact);
            return query.list();
        }
    }

}
